package com.acme.domain.bank;

import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.client.Client;
import com.acme.domain.client.Gender;

import java.io.*;
import java.util.StringTokenizer;

public class BankDataLoaderService {

    public Client parseClient(String line) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        String clientName = null;
        Gender clientGender = null;
        double accountBalance = 0;
        double accountOverdraft = -1;
        String accountType = null;
        while (tokenizer.hasMoreTokens()) {
            String elem = tokenizer.nextToken();
            String[] subelems = elem.split("=");
            String value = subelems[1];
            switch (subelems[0]) {
                case "name":
                    clientName = value;
                    break;
                case "gender":
                    switch (value) {
                        case "m": clientGender = Gender.MALE; break;
                        case "f": clientGender = Gender.FEMALE; break;
                        default: clientGender = null;
                    }
                    break;
                case "balance":
                    accountBalance = Double.parseDouble(value);
                    break;
                case "overdraft":
                    accountOverdraft = Double.parseDouble(value);
                    break;
                case "accounttype":
                    accountType = value;
                    break;
                default: break;
            }
        }
        Client client = new Client(clientName, clientGender);
        Account account = null;
        switch (accountType) {
            case "s":
                account = new SavingAccount(accountBalance);
                break;
            case "c":
                account = new CheckingAccount(accountBalance, accountOverdraft);
                break;
            default: break;
        }
        client.addAccounts(account);
        return client;
    }

    public Bank readBankData(String path) throws IOException {
        try (
            BufferedReader in = new BufferedReader(new FileReader(path))
        ) {
            Bank bank = new Bank();
            BankService service = bank.getService();
            String line = null;
            while ((line = in.readLine()) != null) {
                Client client = parseClient(line);
                service.addClient(client);
            }
            return bank;
        }
    }
}
